package com.glinsoft.ticktak.util;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;


public class Download {

    /**
     * 下载文件
     * @param filePath 文件在服务器中的路径
     * @param response
     * @param fileName 保存后的文件名
     */
    public static void downloadFile(String filePath, HttpServletResponse response, String fileName) {
        try {
            response.reset();
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            long fileLength = new File(filePath).length();
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            response.setHeader("Content-Type","application/octet-stream");
            response.setContentType("application/octet-stream");
            bis = new BufferedInputStream(new FileInputStream(filePath));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[1024];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bos.flush();
            bos.close();
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
